package inventory.master.controller;


import implementor.MaterialMasterImplementor;
import implementor.MaterialSpecificationImplementor;
import inventory.master.view.MaterialManagementView;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLIntegrityConstraintViolationException;

import javax.swing.JOptionPane;

import model.Material;

import dao.MaterialMasterDao;
import dao.MaterialSpecificationDao;
import dto.MaterialMaster;
import dto.MaterialSpecification;

import utility.AppUtilities;
import utility.Constants;
import utility.Validater;

public class MaterialManagementController implements ActionListener
{
	private MaterialManagementView view;
	private Material model;
	private MaterialMaster[]material;
	private MaterialSpecification[] specifications;
	private MaterialMasterDao cd;
	private MaterialSpecificationDao specDao;
	private static int index=0;
	
	
/*****************************************CONSTRUCTORS*************************************************************/
	public MaterialManagementController() 
	{
	
	}

	public MaterialManagementController(MaterialManagementView view,  Material model) 
	{
		super();
		this.view = view;
		this.model = model;
		view.actionListener(this);
		  cd=new MaterialMasterImplementor();
		  specDao=new MaterialSpecificationImplementor();
		try 
		{
			material=cd.retreiveAll();
			specifications=specDao.retreiveAll();
		} catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}

/**********************************************STATIC PART*************************************************************/	
	
	private void reactOnSave()
	{
		String materialName=view.gettMaterialName().getText();
		String mCode=AppUtilities.getmCode(materialName);
		String catName=view.getCategorycombo().getSelectedItem().toString();
		String catcode=AppUtilities.getCategoryName(catName);
		String mspec=view.gettSpecification().getSelectedItem().toString();
		
		String unit=view.gettUnit().getText();
		MaterialMaster mat=new MaterialMaster(materialName, materialName, catcode, Constants.ACTIVE, unit);
		MaterialSpecification specs=new MaterialSpecification(0, mCode, mspec, Constants.ACTIVE);
	
		
		try
		{
			cd.add(mat);
			specDao.add(specs);
			material=cd.retreiveAll();
			specifications=specDao.retreiveAll();  // refresh the  Material array
			index=0;
			JOptionPane.showMessageDialog(null, "Data successfully added");
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
			e.printStackTrace();
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
			e.printStackTrace();
		
		}
		
		
	}
	
	private void toggleStatus() throws Exception
	{
		String matName=view.gettMaterialName().getText();
		cd=new MaterialMasterImplementor();
		
		MaterialMaster master=null;
		
		try
		{
			master=cd.retreive("mName", matName);
			
			if(view.getLblActive().getText().equals("ACTIVE"))
			{
			       master.setStatus(Constants.INACTIVE);
			       
			      
			}
			if(view.getLblActive().getText().equals("INACTIVE"))
			{
				master.setStatus(Constants.ACTIVE);
				
			}
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
		}
		cd.delete(master);
	}
	
	private void reactOnUpdate() throws Exception
	{
		String matname=view.gettMaterialName().getText();
		
		MaterialMaster master=cd.retreive("mName", matname);
		master.setmName(matname);
		
		try
		{
			cd.update(master);
			JOptionPane.showMessageDialog(null, "Data successfully updated");
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
		
		}
		// The database is updated now , get all the sellers again
		 this.material=cd.retreiveAll();
	}
	
	private void reactOnSearch() throws Exception
	{
		String matname=view.gettMaterialName().getText();
		
		MaterialMaster master=cd.retreive("mName", matname);
		master.setmName(matname);
		
		try
		{
		 master=cd.retreive( "mName", matname);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		fillViewFormFromModel();
		// search has been done we need to update the index
		for(int i =0;i<material.length;i++)
			{
			  if(material[i].equals(matname))
			  {
				  index=i;
			  }
			}
	}
	

	private void reactOnBack() throws Exception
	{
		if(index>-1)
		{
		model.setMaterial(this.material[index]);
		fillViewFormFromModel();
		index=index-1;
		}
		else
			index=0;
	}
	
   private void reactOnForward() throws Exception
	{
		if(index<material.length && index>-1)
		{
			model.setMaterial(this.material[index]);
			fillViewFormFromModel();
			index=index+1;
		}		
	}
	
	private void fillViewFormFromModel()
	{
		view.gettMcode().setText(model.getMCode());
		view.gettMaterialName().setText(model.getMname());
		view.gettUnit().setText(model.getUnit());
		String matCode=view.gettMcode().getText();
		AppUtilities.fillSpecificationCombo(view.gettSpecification(), matCode);
		if(model.getMasterStatus() == 1)
		  {
			view.getLblActive().setText("ACTIVE");
			view.getBtnStatus().setText("DEACTIVATE");
		  }
		if(model.getMasterStatus() == 0)
		  {
			view.getLblActive().setText("INACTIVE");
			view.getBtnStatus().setText("ACTIVATE");
		  }
		
	}
	
	
/**********************************************DYNAMIC PART*************************************************************/	
	

	@Override
	public void actionPerformed(ActionEvent arg0) 
	{
		String k=arg0.getActionCommand();
		Validater validates = new Validater(view);
		String message = validates.validateForEmpty();
		if(k.contains("SAVE"))
		{

			if(message.equals(""))
			{
				reactOnSave();
				validates.refresh();
			}
			else
				JOptionPane.showMessageDialog(null, message);
			
			
		}
		if(k.contains("MARK INACTIVE"))
		{
			try {

				if(message.equals(""))
				{
					toggleStatus();
					validates.refresh();
				}
				else
					JOptionPane.showMessageDialog(null, message);
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("UPDATE"))
		{
			try {

				if(message.equals(""))
				{
					reactOnUpdate();
					validates.refresh();
				}
				else
					JOptionPane.showMessageDialog(null, message);
				
			
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("<<"))
		{
			try {
				System.out.println("Back");
				reactOnBack();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("SEARCH"))
		{
			try 
			{
				if(message.equals(""))
				{
					reactOnSearch();
					validates.refresh();
				}
				else
					JOptionPane.showMessageDialog(null, message);
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains(">>"))
		{
			try {
				reactOnForward();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("CLEAR"))
		{
			
		}
		if(k.contains("EXIT "))
		{
			
		}
		
	}

}
